<?php

function download_branch_zip($branch, $target)
{
    $url = 'https://gitee.com/Discuz/DiscuzX/repository/archive/' . $branch . '.zip';
    logging\info('start downloading %s', $url);
    $newf = fopen($target, 'wb');
    if (!$newf) {
        logging\error("cannot create file %s", $target);
        exit(1);
    }
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FILE, $newf);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'curl/7.64.1');
    // curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'progress');
    curl_setopt($ch, CURLOPT_NOPROGRESS, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $proxy = getenv("http_proxy");
    if ($proxy) {
        logging\info("setting proxy as %s", $proxy);
        curl_setopt($ch, CURLOPT_PROXY, $proxy);
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    }

    logging\log(LOG_LEVEL_INFO, '    downloaded: 0 KB');
    curl_exec($ch);
    curl_close($ch);
    echo "\n";

    fclose($newf);
}

function progress($resource, $download_size, $downloaded, $upload_size, $uploaded)
{
    echo "\r";
    logging\log(LOG_LEVEL_INFO, '    downloaded: %d KB', $downloaded / 1000);
}

function get_last_commit_id($branch) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, "https://gitee.com/Discuz/DiscuzX/tree/" . $branch . "/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $contents = curl_exec($ch);
    curl_close($ch);

    if (preg_match('/class="repo-index-commit-msg".*?href="\/Discuz\/DiscuzX\/commit\/(.*)"/m', $contents, $m)) {
        return substr($m[1], 0, 8);
    }
    if (preg_match('/href="\/Discuz\/DiscuzX\/commit\/(.*)".*?class="repo-index-commit-msg"/m', $contents, $m)) {
        return substr($m[1], 0, 8);
    }
    return FALSE;
}